package com.gamota.mobi.network;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.gamota.mobi.R;
import com.gamota.mobi.util.StorageUtils;
import com.gamota.mobi.util.Utils;

public class DownloadUpdateTask extends AsyncTask<String, Integer, Integer>{
	
	private Context context;
	private ProgressDialog mProgressDialog;
	private String savePath = "";
	private IDownloadUpdateCallback callback;
	
	public DownloadUpdateTask(Context context){
		this.context = context;
	}
	
	public void setDownloadCallback(IDownloadUpdateCallback c){
		this.callback = c;
	}

	@Override
	protected Integer doInBackground(String... params) {
		// TODO Auto-generated method stub
		int count;
		File file = new File(StorageUtils.APPS_ROOT);
		if (!file.exists()) {
			file.mkdirs();
		}
		savePath = file + File.separator + Utils.getFileName(params[0]);
		try {
			URL url = new URL(params[0]);
			URLConnection conn = url.openConnection();
			conn.connect();
			int lenghtOfFile = conn.getContentLength();
			InputStream input = new BufferedInputStream(url.openStream());
			OutputStream output = new FileOutputStream(savePath);
			byte data[] = new byte[1024];
			long total = 0;
			while ((count = input.read(data)) != -1) {
				total += count;
				publishProgress((int) (total * 100 / lenghtOfFile));
				output.write(data, 0, count);
			}
			output.flush();
			output.close();
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		return 0;
	}
	
	@Override
	protected void onPostExecute(Integer result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if(result == -1){
			Toast.makeText(context, R.string.connect_error, Toast.LENGTH_SHORT).show();
			callback.onDownloadError();
		} else {
			callback.onDownloadComplete(savePath);
		}
		mProgressDialog.dismiss();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		mProgressDialog.setProgress(values[0]);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mProgressDialog = new ProgressDialog(context);
		mProgressDialog.setMessage(context.getResources().getString(R.string.downloading_update));
		mProgressDialog.setCancelable(false);
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.show();
	}

}
